package com.ym.medical.service.impl;

import com.ym.core.utils.tkmybatis.BaseSVImpl;
import com.ym.core.utils.tkmybatis.TK;
import com.ym.medical.dao.UserLikeRecordDao;
import com.ym.medical.domain.entity.UserLikeRecordEntity;
import com.ym.medical.domain.param.UserLikeRecordQueryParam;
import com.ym.medical.domain.param.UserLikeRecordUpdateParam;
import com.ym.medical.domain.vo.UserLikeRecordListPcVO;
import com.ym.medical.enums.CommentTypeEnum;
import com.ym.medical.service.IUserLikeRecordSV;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户点赞Service业务层处理
 *
 * @author ym
 * @date 2020-08-24
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserLikeRecordSVImpl extends BaseSVImpl<UserLikeRecordEntity, UserLikeRecordDao> implements IUserLikeRecordSV {

    /**
     * 查询用户点赞列表
     *
     * @param queryParam 用户点赞 查询参数
     * @return 用户点赞
     */
    @Override
    public List<UserLikeRecordListPcVO> selectListPC(UserLikeRecordQueryParam queryParam) {
        List<UserLikeRecordListPcVO> userLikeRecords = mapper.selectListPC(queryParam);
        return userLikeRecords;
    }

    /**
     * 新增用户点赞
     *
     * @param updateParam 用户点赞 新增参数
     * @return 结果
     */
    @Override
    public Long insertPC(UserLikeRecordUpdateParam updateParam) {
        UserLikeRecordEntity entity = updateParam.covert();
        this.insert(entity);
        return entity.getId();
    }

    /**
     * 修改用户点赞
     *
     * @param updateParam 用户点赞 修改参数
     * @return 结果
     */
    @Override
    public int updateByIdPC(UserLikeRecordUpdateParam updateParam) {
        UserLikeRecordEntity entity = updateParam.covert();
        int result = this.updateById(entity);
        return result;
    }

    @Override
    public void doLike(Long loginId, Long id, CommentTypeEnum commentTypeEnum) {
        List<UserLikeRecordEntity> userLikeRecordEntities = selectList(TK.select(UserLikeRecordEntity.class)
                .where()
                .andEqualTo(UserLikeRecordEntity::getPlate, commentTypeEnum.getKey())
                .andEqualTo(UserLikeRecordEntity::getUpPerson, loginId)
                .andEqualTo(UserLikeRecordEntity::getRecordId, id)
                .end());
        if(!userLikeRecordEntities.isEmpty()){
            deleteByIds((Long[]) userLikeRecordEntities.stream().map(n->n.getId()).collect(Collectors.toList()).toArray());
        }else {
            insert(UserLikeRecordEntity
                    .builder()
                    .plate(commentTypeEnum.getKey())
                    .recordId(id)
                    .upPerson(loginId)
                    .build());
        }
    }
}
